package drrr.orm;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import java.util.List;

/**
 * operate the Room table
 * <b>do not use this class in other package</b>
 * Created by Xun on 2015/4/28.
 */
class RoomDao extends HibernateDaoSupport {
    private static final Log log = LogFactory.getLog(RoomDao.class);

    /**
     * delete a existed roomEntity
     *
     * @param roomEntity a existed roomEntity
     */
    public void delete(RoomEntity roomEntity) {
        Session session = getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        session.delete(roomEntity);
        transaction.commit();
        session.close();
    }

    /**
     * insrt a new  RoomEntity to the database
     *
     * @param roomEntity
     */
    public void insert(RoomEntity roomEntity) {
        Session session = getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        session.save(roomEntity);
        transaction.commit();
        session.close();
    }

    /**
     * update the room
     *
     * @param roomEntity the modified RoomEntity
     */
    public void update(RoomEntity roomEntity) {
        Session session = getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        session.update(roomEntity);
        transaction.commit();
        session.close();
    }

    /**
     * get all of the rooms
     *
     * @return the list of rooms
     */
    public List getAllRooms() {
        Session session = getSessionFactory().openSession();
        List list = null;
        try {
            list = session.createQuery("from RoomEntity ").list();
        } catch (Exception e) {
            list = session.createQuery("from RoomEntity ").list();
        }
        session.close();
        return list;
    }

    /**
     * find room by the roomid
     *
     * @param roomid identity of the room
     * @return null if noe exists or the specified object
     */
    public RoomEntity find(int roomid) {
        List entitylist = getSessionFactory().openSession().createQuery("from RoomEntity where id=" + roomid).list();
        if (entitylist.size() == 0) {
            return null;
        } else// if(entitylist.size()==1)
        {
            return (RoomEntity) entitylist.get(0);
        }
    }
}
